package yxy.game.pm2.command.tower;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.module.rank.RankEntry;
import yxy.game.pm2.bean.module.rank.RankWorship;
import yxy.game.pm2.bean.module.rank.RankWorshipPlayer;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.TowerMessage;
import yxy.game.pm2.module.player.PlayerHandle;
import yxy.game.pm2.module.tower.RankTower;

import java.util.Collection;

/** 修炼塔 修炼塔排行榜 */
@MessageType(proto = Command.TowerRank, classtype = TowerMessage.TowerRankRequest.class)
public class CMD_TowerRank extends Command<TowerMessage.TowerRankRequest> {

	@Override
	public void execute(MessageSource messageSource, TowerMessage.TowerRankRequest request) {
		String playerCode = messageSource.getTag();

		TowerMessage.TowerRankResponse.Builder response = TowerMessage.TowerRankResponse.newBuilder();

		RankTower rankTower = RankTower.getRank(playerCode);
		try {
			PlayerHandle playerHandle = new PlayerHandle();
			RankWorship worship = rankTower.getWorship();
			RankWorshipPlayer worshipPlayer = RankWorshipPlayer.get(playerCode, worship);

			Collection<RankEntry> top = rankTower.top(rankTower.topSize());
			int rank = 0;
			for (RankEntry entry : top) {
				String pCode = entry.getKey();
				int floor = entry.getValue().intValue();

				TowerMessage.RankTower.Builder builder = TowerMessage.RankTower.newBuilder();
				builder.setRank(++rank);
				builder.setPlayerInfo(playerHandle.playerSimpleInfo(pCode));
				builder.setFloor(floor);
				builder.setFans(worship.getScore(pCode));
				builder.setLiked(worshipPlayer.getWorshiped().contains(pCode));
				response.addRank(builder);
			}

			{
				int playerRank = 0;
				int floor = 0;
				RankEntry entry = rankTower.get(playerCode);
				if (entry != null) {
					playerRank = rankTower.rank(playerCode);
					floor = entry.getValue().intValue();
				}

				TowerMessage.RankTower.Builder builder = TowerMessage.RankTower.newBuilder();
				builder.setRank(playerRank);
				builder.setPlayerInfo(playerHandle.playerSimpleInfo(playerCode));
				builder.setFloor(floor);
				response.setMy(builder);
			}

			response.setTimes(worshipPlayer.remainTimes());

			send(messageSource, response, Result.Success);
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		}
	}

	private void send(MessageSource messageSource, TowerMessage.TowerRankResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}